package com.yolib.sanyi.connection.event;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

//import com.yolib.costco.RestartReceiver;
import com.yolib.sanyi.tool.Utility;
import com.yolib.sanyi.tool.YoliBLog;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;

public abstract class ConnectionEvent {

	protected Handler mHandler;
	protected ConnectionEvent mSubEvent;

	public static int ConnectionTimeOut = 5000;
	public static int SocketTimeOut = 5000;

	public static String E402 = "Connection.SocketTimeOut";
	public static String E403 = "Connection.Unknow.Error";
	public static String E404 = "Connection.Error";
	// public static String E405 = "User Name not exist";
	// public static String E406 = "Pwd Error";
	// public static String E407 = "Phone not exist";
	// public static String E408 = "ApiKey is wrong";
	// public static String E409 = "Token is invalidate"; //�����sLOGIN
	public static String E410 = "ERROR 500";
	public static String SUCCESSFUL = "Connection.successful";
	public static final String CONNECTION_ERROR = "Error";

	public static final int SUCCESS = 10001;
	public static final int PLEASE_LOGIN_FIRST = 10003;
	public static final int ERROR = 10004;

	public static final int RETRY_MAX = 3;

	public abstract void post();

	private int retry = 0;

	public String httpPost(String param, Context context) {
		HttpClient hc = new DefaultHttpClient();

		HttpParams params = hc.getParams();
		HttpConnectionParams.setConnectionTimeout(params, ConnectionTimeOut);
		HttpConnectionParams.setSoTimeout(params, SocketTimeOut);

		if (retry == RETRY_MAX)
			return CONNECTION_ERROR;

		HttpResponse rp = null;
		try {
			HttpPost post = null;
			if (param != null && !param.equals("")) {
				post = new HttpPost(Utility.getTESTAPIURL() + param);// +
																		// API_NAME);
				YoliBLog.d("yolib : yolib.http.url= " + post.getURI());
			}
			rp = hc.execute(post);
			String resp_str = rp.toString();
			InputStream is = rp.getEntity().getContent();
			byte[] data = new byte[1024];
			String str = "";
			while ((is.read(data)) != -1)
				str += new String(data);

			if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK && rp != null && str.contains("Connect OK!!")) {
				return resp_str;
			} else {
				if (rp.getStatusLine().getStatusCode() == 500) {
					YoliBLog.e(E410);
					return CONNECTION_ERROR;
				} else {
					YoliBLog.e(E404);
					return CONNECTION_ERROR;
				}
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
			retry++;
			if (retry == RETRY_MAX) {
				YoliBLog.d(E404);
				return CONNECTION_ERROR;
			} else
				return this.httpPost(param, context);
		} catch (SocketTimeoutException e) {
			retry++;
			if (retry == RETRY_MAX) {
				YoliBLog.e(E402);
				return CONNECTION_ERROR;
			} else
				return this.httpPost(param, context);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		retry++;
		if (retry == RETRY_MAX) {
			YoliBLog.e(E402);
			return CONNECTION_ERROR;
		} else
			return this.httpPost(param, context);
	}

	public String httpPost(List<NameValuePair> nameValuePairs, Context context) {
		HttpClient hc = new DefaultHttpClient();

		HttpParams params = hc.getParams();
		HttpConnectionParams.setConnectionTimeout(params, ConnectionTimeOut);
		HttpConnectionParams.setSoTimeout(params, SocketTimeOut);
		// if(output != null)
		// YoliBLog.e("timespace.http.output="+output);
		if (retry == RETRY_MAX)
			return CONNECTION_ERROR;

		HttpPost post = new HttpPost(Utility.getAPIHost());// + API_NAME);

		YoliBLog.d("yolib : yolib.http.url= " + post.getURI());
		HttpResponse rp = null;
		try {
			if (nameValuePairs != null) {
				post.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
			}
			rp = hc.execute(post);
			if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK && rp != null) {
				String resp_str = EntityUtils.toString(rp.getEntity());
				YoliBLog.d("yolib.http.input= " + resp_str);
				// 11-14 17:20:08.250: E/YoLiB(9632): linespace
				// resp:{"sameKey":true,"result":{"errorCode":"E006","errorMsg":"AuthToken\u8a8d\u8b49\u932f\u8aa4"}}

				return resp_str;
			} else {
				if (rp.getStatusLine().getStatusCode() == 500) {
					YoliBLog.e(E410);
					return CONNECTION_ERROR;
				} else {
					YoliBLog.e(E404);
					return CONNECTION_ERROR;
				}
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
			retry++;
			if (retry == RETRY_MAX) {
				YoliBLog.d(E404);
				return CONNECTION_ERROR;
			} else
				return this.httpPost(nameValuePairs, context);
		} catch (SocketTimeoutException e) {
			retry++;
			if (retry == RETRY_MAX) {
				YoliBLog.e(E402);
				return CONNECTION_ERROR;
			} else
				return this.httpPost(nameValuePairs, context);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		retry++;
		if (retry == RETRY_MAX) {
			YoliBLog.e(E402);
			return CONNECTION_ERROR;
		} else
			return this.httpPost(nameValuePairs, context);
	}

	public String httpGet(String url, List<NameValuePair> params) {

		HttpClient hc = new DefaultHttpClient();

		HttpParams httpParams = hc.getParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, ConnectionTimeOut);
		HttpConnectionParams.setSoTimeout(httpParams, SocketTimeOut);

		if (retry == RETRY_MAX)
			return CONNECTION_ERROR;

		try {
			//
//			StringBuilder sb = new StringBuilder();
//			
//		    for(Map.Entry<String, String> entry : params.entrySet()){  
//		        sb.append(entry.getKey()).append('=')  
//		            .append(URLEncoder.encode(entry.getValue(), "utf-8")).append('&');  
//		    }  
//		    sb.deleteCharAt(sb.length()-1);//删除最後一個"&"  
//			
//		    YoliBLog.e("ken", sb.toString());
		    
			HttpResponse response = hc.execute( new HttpGet( params == null || params.size() == 0 ? url : url + "&" + URLEncodedUtils.format(params, "utf-8")));
			HttpEntity result = response.getEntity();
			if (result != null) {
				// return EntityUtils.toString(result); // 有編碼問題
				InputStream mInputStream = result.getContent();
				String out = getStringFromInputStream(mInputStream);
				mInputStream.close();
				return out;
			} else {
				if (response.getStatusLine().getStatusCode() == 500) {
					YoliBLog.e(E410);
					return CONNECTION_ERROR;
				} else {
					YoliBLog.e(E404);
					return CONNECTION_ERROR;
				}
			}

		} catch (UnknownHostException e) {
			e.printStackTrace();
			retry++;
			if (retry == RETRY_MAX) {
				YoliBLog.d(E404);
				return CONNECTION_ERROR;
			} else
				return this.httpGet(url, params);
		} catch (SocketTimeoutException e) {
			retry++;
			if (retry == RETRY_MAX) {
				YoliBLog.e(E402);
				return CONNECTION_ERROR;
			} else
				return this.httpGet(url, params);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		retry++;
		if (retry == RETRY_MAX) {
			YoliBLog.e(E402);
			return CONNECTION_ERROR;
		} else
			return this.httpGet(url, params);
	}

	private String getStringFromInputStream(InputStream in) {
		byte[] data = new byte[1024];
		int length;
		if (in == null)
			return null;
		ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
		try {
			while ((length = in.read(data)) != -1)
				mByteArrayOutputStream.write(data, 0, length);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return new String(mByteArrayOutputStream.toByteArray());
	}

	public void setHandler(Handler handler) {
		mHandler = handler;
	};

	public void addSubEvent(ConnectionEvent event) {
		mSubEvent = event;
	};

}
